//
//  QueryMessageService.m
//  OMS
//
//  Created by goldeney on 14-10-16.
//  Copyright (c) 2014年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "QueryMessageService.h"
#import "DspMD5Util.h"
#import "ServiceConnect.h"
#import "ModuleAuthorityEntity+CoreDataClass.h"

#import "ExitLoginService.h"
#import "NSArray+Format.h"

#import "NSKeyedArchiverUserLogin.h"
#import "UserLoginNSCoding.h"
#import "NSDictionary+DataFormat.h"

#import "OAMyApplyViewController.h"
#import "OAMyApprovalViewController.h"
#import "OAMyBriefcaseViewController.h"
#import "JCSubMViewController.h"

@interface QueryMessageService()

@property (nonatomic,strong) NSTimer *queryMessageTimer;

@end

#define QueryCirculationTime 5.0
static QueryMessageService *sharedMessageService = nil;

@implementation QueryMessageService

+ (QueryMessageService*)sharedService
{
    @synchronized(self){
        if (sharedMessageService == nil){
            sharedMessageService = [[self alloc] init];
        }
    }
    return sharedMessageService;
}

#pragma mark 消息查询

- (void)startQueryMessage
{
    if (!self.queryMessageTimer) {
        UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
        //判断用户是否登录
        if (userInfo) {
            self.queryMessageTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(executeTimer) userInfo:nil repeats:YES];
        }
    }
}

- (void)executeTimer
{
    //暂停定时器
    [self.queryMessageTimer setFireDate:[NSDate distantFuture]];
    
    //判断用户是否登录
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    if (!userInfo) {
        [ExitLoginService exitAppUserLogin];
        return;
    }
    
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userInfo.Id forKey:@"userid"];
    
    //获取消息信息表数据
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_getOffice_App_Masge" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if (result.resultArray && result.resultArray.count>0) {
            [self messageToProcess:result.resultArray];
        }
        //开启定时器
        [self.queryMessageTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:QueryCirculationTime]];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"系统错误，请重新尝试连接:%@",error);
        //开启定时器
        [self.queryMessageTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:QueryCirculationTime]];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"网络异常:%@",error);
        //开启定时器
        [self.queryMessageTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:QueryCirculationTime]];
    }];
}

- (void)messageToProcess:(NSArray*)results
{
    //(0)用户设备检查（防止同时在线）
    NSArray *specialInfo = [results objectAtIndex:1];
    [self userSpecialInfoManage:specialInfo];
    
}

- (void)stopQueryMessage
{
    if (self.queryMessageTimer){
        [self.queryMessageTimer setFireDate:[NSDate distantFuture]];
        [self.queryMessageTimer invalidate];
        self.queryMessageTimer = nil;
    }
    //清理对象
    sharedMessageService = nil;
}

#pragma mark -
#pragma mark - SQLite Operation

- (BOOL)userSpecialInfoManage:(NSArray*)specialInfo
{
    //下线类型(1为登录手机用到，2为修改密码，3为角色权限设置，4为账户注销)
    if (!(specialInfo && specialInfo.count>0)) return YES;
    UserLoginNSCoding *userInfos = [NSKeyedArchiverUserLogin getUserLoginData];
    if(!userInfos) return YES;
    
    NSDictionary *temp = [specialInfo firstObject];
    NSString *Mark = [temp objectFormatStringForKey:@"WhetherOnline"];
    NSInteger MarkZT = [[temp objectFormatForKey:@"WhetherType"] integerValue];
    
    if ([Mark isEqualToString:userInfos.WhetherOnline]) return NO;
    if (MarkZT == 2) { //密码变更
        [ExitLoginService exitAppUserLogin];
        NSString *message = @"您的账号登录密码已被修改，若不是您本人操作，请联系相关管理员";
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:message delegate:nil
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return YES;
        
    } else if (MarkZT == 3) { //当前用户角色权限设置变更
        [ExitLoginService exitAppUserLogin];
        NSString *message = @"您的账号权限已变更，若有疑问请联系相关管理员";
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:message delegate:nil
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return YES;
        
    } else if (MarkZT == 4) { //当前账号已被停止时退出登录
        [ExitLoginService exitAppUserLogin];
        NSString *message = @"您的账号已被停止使用，若有疑问请联系相关管理员";
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:message delegate:nil
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return YES;
        
    } else if (MarkZT == 1) { //当前用户设备信息不同时退出登录
        [ExitLoginService exitAppUserLogin];
        NSString *message = @"您的账号已在其他设备上登录，若不是您本人操作，请联系相关管理员";
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:message delegate:nil
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return YES;
        
    } else { //未知情况下线
        [ExitLoginService exitAppUserLogin];
        NSString *message = @"系统检查到您的账号当前不安全，若有疑问请联系相关管理员";
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:message delegate:nil
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return YES;
    }
}

@end
